package com.banquetmanagementsystem.interceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.banquetmanagementsystem.common.Utils.TokenUtil;
import com.banquetmanagementsystem.common.Utils.TokenUtilProperties;
import com.banquetmanagementsystem.common.context.BaseContext;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * 短视效token拦截器
 * @author 86176
 */
@Component
public class JwtAccessTokenInterceptor implements HandlerInterceptor {
    @Resource(name = "tokenUtilProperties")
    private TokenUtilProperties tokenUtilProperties;
    @Resource(name = "tokenUtil")
    private TokenUtil tokenUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String accessToken = request.getHeader(tokenUtilProperties.getAccessTokenName());
        if (accessToken== null || !tokenUtil.verifyAccessToken(accessToken)){
            return response(response);
        }
        return true;
    }

    private Boolean response(HttpServletResponse response) throws IOException, JSONException {
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        JSONObject json = new JSONObject();
        json.put("code", "401");
        json.put("msg", "accessToken失效");
        json.put("data", "");
        out.print(json);
        out.close();
        return false;
    }
}
